import {
    getCategory,
} from '@/api/index.js'

const state = {
    cateList: sessionStorage.getItem('CATEGORY_LIST') != null ?
        JSON.parse(sessionStorage.getItem('CATEGORY_LIST')) : [],
    cateNum: sessionStorage.getItem('CATEGORY_NUM') != null ?
        sessionStorage.getItem('CATEGORY_NUM') : 0,
}

// 同步方法
const mutations = {
    SET_CATEGORY_NUM(state, cateNum) {
        if (cateNum) {
            state.cateNum = cateNum
            sessionStorage.setItem('CATEGORY_NUM', cateNum)
        } else {
            state.cateNum = 0
            sessionStorage.removeItem('CATEGORY_NUM')
        }
    },
    SET_HOT_CATEGORY_LIST(state, cateList) {
        if (cateList) {
            state.cateHotList = cateList
            sessionStorage.setItem('CATEGORY_HOT_LIST', JSON.stringify(cateList))
        } else {
            state.cateHotList = []
            sessionStorage.removeItem('CATEGORY_HOT_LIST')
        }
    },
    SET_CATEGORY_LIST(state, cateList) {
        if (cateList) {
            state.cateList = cateList
            sessionStorage.setItem('CATEGORY_LIST', JSON.stringify(cateList))
        } else {
            state.cateList = []
            sessionStorage.removeItem('CATEGORY_LIST')
        }
    },
}

// 异步方法
const actions = {
    async getCate({
        commit
    }) {
        try {
            const response = await getCategory()
            const {
                code,
                data
            } = response
            if (code === 200) {
                const total = data.length
                const result = data.map((e) => {
                    return {
                        id: e.id,
                        name: e.categoryName
                    }
                })
                result.unshift({
                    id: 0,
                    name: '全部'
                })
                commit('SET_CATEGORY_NUM', total)
                commit('SET_CATEGORY_LIST', result)
                return Promise.resolve()
            } else {
                // return Promise.reject(message)
            }
        } catch (e) {
            console.log(e)
        }
    },
}

export default {
    namespaced: true,
    mutations,
    actions,
    state,
}